package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.AliasEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.enums.FundAccountTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.model.impl.PaasProcessDataModelImpl;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.ReflectHelper;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.FundAccountErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.fundaccount.pojo.dto.FundAccountAddDTO;
import com.xbongbong.pro.fundaccount.pojo.dto.FundAccountBatchUpdateDTO;
import com.xbongbong.pro.fundaccount.pojo.dto.FundAccountDeleteDTO;
import com.xbongbong.pro.fundaccount.pojo.dto.FundAccountGetDTO;
import com.xbongbong.pro.fundaccount.pojo.dto.FundAccountStatusDTO;
import com.xbongbong.pro.fundaccount.pojo.vo.FundAccountAddVO;
import com.xbongbong.pro.fundaccount.pojo.vo.FundAccountGetVO;
import com.xbongbong.pro.fundaccount.pojo.vo.FundAccountStatusVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.InvoiceConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.FundAccountEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.FundAccountModel;
import com.xbongbong.saas.service.FundAccountService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author zhouwq
 * @date 2019/10/23 10:33
 */

@Service("fundAccountService")
public class FundAccountServiceImpl implements FundAccountService {

    private static final Logger LOG = LoggerFactory.getLogger(FundAccountServiceImpl.class);

    private static final int ACCOUNT_MAX_SIZE = 50;

    private static final int ACCOUNT_NAME_MAX_LENGTH = 50;

    @Resource
    private FundAccountModel fundAccountModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasProcessDataModelImpl paasProcessDataModel;
    @Resource
    private PaasAppService paasAppService;

    @Override
    public FundAccountAddVO add(FundAccountAddDTO fundAccountAddDTO) throws XbbException {
        FundAccountAddVO fundAccountAddVO = new FundAccountAddVO();
        if (fundAccountAddDTO.getEntity() != null) {
            //校验信息
            verifyFundAccount(fundAccountAddDTO.getEntity());
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, fundAccountAddDTO.getCorpid());
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            Integer count = fundAccountModel.getEntitysCount(param);
            if (count >= ACCOUNT_MAX_SIZE) {
                throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000008.getCode(), String.format(FundAccountErrorCodeEnum.API_ERROR_1000008.getMsg(), ACCOUNT_MAX_SIZE));
            }
            FundAccountEntity fundAccountEntity = fundAccountAddDTO.getEntity();
            fundAccountEntity.setCorpid(fundAccountAddDTO.getCorpid());
            fundAccountEntity.setDel(DelEnum.NORMAL.getDel());
            fundAccountEntity.setEnable(EnableEnum.OPEN.getCode());
            fundAccountEntity.setCreatorId(fundAccountAddDTO.getUserId());
            fundAccountEntity.setAddTime(DateTimeUtil.getInt());
            fundAccountEntity.setUpdateTime(DateTimeUtil.getInt());
            fundAccountEntity.setAmount(fundAccountEntity.getInitialAmount());
            try {
                fundAccountModel.insert(fundAccountEntity);
            } catch (Exception e) {
                LOG.error("新增资金账户出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
        }
        return fundAccountAddVO;
    }

    @Override
    public FundAccountAddVO update(FundAccountAddDTO fundAccountAddDTO) throws XbbException {
        FundAccountAddVO fundAccountAddVO = new FundAccountAddVO();
        if (fundAccountAddDTO.getEntity() != null) {
            //校验信息
            verifyFundAccount(fundAccountAddDTO.getEntity());
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put(StringConstant.CORPID, fundAccountAddDTO.getCorpid());
            params.put(StringConstant.SAAS_LINK_BUSINESS_ID, fundAccountAddDTO.getEntity().getId());
            params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<FundAccountEntity> oldEntityList = fundAccountModel.findEntitys(params);
            if (oldEntityList == null || oldEntityList.size() == 0) {
                throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000009);
            }
            FundAccountEntity oldEntity = oldEntityList.get(0);
            FundAccountEntity fundAccountEntity = fundAccountAddDTO.getEntity();
            if (fundAccountEntity.getInitialAmount() != null) {
                BigDecimal addValue = fundAccountEntity.getInitialAmount().subtract(oldEntity.getInitialAmount());
                fundAccountEntity.setAmount(oldEntity.getAmount().add(addValue));
            }
            fundAccountEntity.setUpdateTime(DateTimeUtil.getInt());
            try {
                fundAccountModel.update(fundAccountEntity);
            } catch (Exception e) {
                LOG.error("更新资金账户出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
        }
        return fundAccountAddVO;
    }

    @Override
    public FundAccountAddVO delete(FundAccountDeleteDTO fundAccountDeleteDTO) throws XbbException {
        FundAccountAddVO fundAccountAddVO = new FundAccountAddVO();
        Long dataId = fundAccountDeleteDTO.getDataId();
        if (dataId != null) {
            String corpid = fundAccountDeleteDTO.getCorpid();
            boolean isExistSheet = verifyFundAccountInSheet(dataId, corpid);
            boolean whetherCanDel = verifyFundAccountWhetherCanDel(dataId, corpid);
            if (!isExistSheet) {
                if (whetherCanDel) {
                    fundAccountModel.deleteByKey(dataId);
                } else {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000004);
                }
            } else {
                throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000003);
            }
        } else {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007, I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_ID));
        }
        return fundAccountAddVO;
    }

    @Override
    public FundAccountStatusVO changeEnableStatus(FundAccountStatusDTO fundAccountStatusDTO) throws XbbException {
        FundAccountStatusVO fundAccountStatusVO = new FundAccountStatusVO();
        Long id = fundAccountStatusDTO.getId();
        Integer enable = fundAccountStatusDTO.getEnable();
        if (id != null && enable != null) {
            EnableEnum enableEnum = EnableEnum.getByCode(enable);
            if (Objects.equals(enable, EnableEnum.CLOSE.getCode())) {
                boolean whetherCanDel = verifyFundAccountWhetherCanClose(fundAccountStatusDTO.getCorpid());
                if (!whetherCanDel) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000004);
                }
            }
            fundAccountModel.updateEnable(id, enable);
            fundAccountStatusVO.setMsg(enableEnum.getMemo());
        } else {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007, I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_ID_STATUS));
        }
        return fundAccountStatusVO;
    }

    @Override
    public FundAccountGetVO getFundAccountsByStatus(String corpid, Integer status) throws XbbException {
        FundAccountGetVO fundAccountGetVO = new FundAccountGetVO();
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        if (status != null) {
            params.put("enable", status);
        }
        List<FundAccountEntity> results;
        try {
            results = fundAccountModel.findEntitys(params);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        fundAccountGetVO.setResults(results);
        return fundAccountGetVO;
    }

    @Override
    public FundAccountGetVO getFundAccounts(FundAccountGetDTO fundAccountGetDTO) throws XbbException {
        FundAccountGetVO fundAccountGetVO = new FundAccountGetVO();
        boolean distributorIsOpen = paasAppService.validateAppEnable(null, XbbRefTypeEnum.DISTRIBUTOR.getAlias(), SaasMarkEnum.SAAS.getCode(), fundAccountGetDTO.getCorpid());
        if (distributorIsOpen) {
            fundAccountGetVO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
        }
        String corpid = fundAccountGetDTO.getCorpid();
        String accountName = fundAccountGetDTO.getAccountName();
        Integer type = fundAccountGetDTO.getType();
        Integer enable = fundAccountGetDTO.getEnable();
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put(StringConstant.DEL, DelEnum.NORMAL);
        if (enable != null) {
            params.put("enable", enable);
        }
        if (accountName != null && !Objects.equals("", accountName)) {
            params.put("name", accountName);
        }
        if (type != null) {
            params.put("type", type);
        }
        List<FundAccountEntity> results;
        try {
            results = fundAccountModel.findEntitys(params);
        } catch (Exception e) {
            LOG.error("获取资金账户列表报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        fundAccountGetVO.setResults(results);
        return fundAccountGetVO;
    }

    @Override
    public void saveByPaymentSheetOrPaySheet(Long accountId, Double amount, String corpid) throws XbbException {
//        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//        param.put("id", accountId);
//        param.put("corpid", corpid);
//        List<FundAccountEntity> list = fundAccountModel.findEntitys(param);
//        if (list != null && list.size() > 0) {
//            FundAccountEntity fundAccountEntity = list.get(0);
//            double resultAmount = Arith.add(fundAccountEntity.getAmount().doubleValue(), amount);
//            if (resultAmount >= 0) {
                try {
                    fundAccountModel.updateAmount(corpid, accountId, amount);
                } catch (Exception e) {
                    LOG.error("更新资金账户金额异常", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
//            }
//            else {
//                throw new XbbException(ErrorCodeEnum.API_ERROR_1000005);
//            }
//        }
    }

    @Override
    public void saveBatchByPaymentSheetOrPaySheet(Map<Long, Double> fundAccountToAmountMap) throws XbbException {
        try {
            List<FundAccountEntity> list = new ArrayList<>();
            fundAccountToAmountMap.forEach((key, value) -> {
                FundAccountEntity fundAccountEntity = new FundAccountEntity();
                BigDecimal amount = BigDecimal.valueOf(value);
                fundAccountEntity.setAmount(amount);
                fundAccountEntity.setId(key);
                list.add(fundAccountEntity);
            });
            int count = list.size();
            if (count > 0) {
                int start = 0;
                int pageNum = 1000;
                for (; start <= count; start = start + pageNum) {
                    // 分组数据的endIndex
                    int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                    List<FundAccountEntity> result = list.subList(start, endIndex);
                    try {
                        fundAccountModel.updateBatchAmount(result);
                    } catch (XbbException e) {
                        StringBuilder str = new StringBuilder();
                        result.forEach(accountEntity -> str.append(accountEntity.getId()).append(","));
                        LOG.error("批量更新资金账户金额异常,异常账户ID为：" + str.toString(), e);
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("批量更新资金账户金额异常", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public FundAccountAddVO updateDefaultAccount(FundAccountBatchUpdateDTO fundAccountBatchUpdateDTO) throws XbbException {
        JSONObject payAccount = fundAccountBatchUpdateDTO.getPayAccount();
        JSONObject paymentAccount = fundAccountBatchUpdateDTO.getPaymentAccount();
        JSONObject weChatPaymentAccount = fundAccountBatchUpdateDTO.getWeChatPaymentAccount();
        JSONObject alipayPaymentAccount = fundAccountBatchUpdateDTO.getAlipayPaymentAccount();
        JSONObject unionPayPaymentAccount = fundAccountBatchUpdateDTO.getUnionPayPaymentAccount();
        //原默认账户ID
        String prePayId = payAccount.getString(StringConstant.PREPAYID);
        String prePaymentId = paymentAccount.getString(StringConstant.PREPAYMENTID);
        //修改后账户ID
        String payId = payAccount.getString("payId");
        String paymentId = paymentAccount.getString(InvoiceConstant.PAYMENT_ID);
        Map<Long, FundAccountEntity> accountIdToEntity = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!Objects.equals(prePayId, payId)) {
            if (prePayId != null && !"".equals(prePayId)) {
                Long id = Long.valueOf(prePayId);
                FundAccountEntity fundAccountEntity = new FundAccountEntity();
                fundAccountEntity.setId(id);
                fundAccountEntity.setIsPayDefault(BasicConstant.ZERO);
                accountIdToEntity.put(id, fundAccountEntity);
            }
            if (payId != null && !"".equals(payId)) {
                Long id = Long.valueOf(payId);
                FundAccountEntity fundAccountEntity = new FundAccountEntity();
                fundAccountEntity.setId(id);
                fundAccountEntity.setIsPayDefault(BasicConstant.ONE);
                accountIdToEntity.put(id, fundAccountEntity);
            }
        }
        if (!Objects.equals(prePaymentId, paymentId)) {
            if (prePaymentId != null && !"".equals(prePaymentId)) {
                Long id = Long.valueOf(prePaymentId);
                FundAccountEntity fundAccountEntity = accountIdToEntity.containsKey(id) ? accountIdToEntity.get(id) : new FundAccountEntity();
                fundAccountEntity.setId(id);
                fundAccountEntity.setIsPaymentDefault(BasicConstant.ZERO);
                accountIdToEntity.put(id, fundAccountEntity);
            }
            if (paymentId != null && !"".equals(paymentId)) {
                Long id = Long.valueOf(paymentId);
                FundAccountEntity fundAccountEntity = accountIdToEntity.containsKey(id) ? accountIdToEntity.get(id) : new FundAccountEntity();
                fundAccountEntity.setId(id);
                fundAccountEntity.setIsPaymentDefault(BasicConstant.ONE);
                accountIdToEntity.put(id, fundAccountEntity);
            }
        }
        formatUpdateAccountMap(weChatPaymentAccount, accountIdToEntity, "isWeChatPaymentDefault");
        formatUpdateAccountMap(alipayPaymentAccount, accountIdToEntity, "isAlipayPaymentDefault");
        formatUpdateAccountMap(unionPayPaymentAccount, accountIdToEntity, "isUnionPayPaymentDefault");
        for (Map.Entry<Long, FundAccountEntity> entry : accountIdToEntity.entrySet()) {
            FundAccountEntity account = entry.getValue();
            fundAccountModel.update(account);
        }
        return new FundAccountAddVO();
    }

    private static void verifyFundAccount(FundAccountEntity fundAccountEntity) throws XbbException{
        Integer type = fundAccountEntity.getType();
        FundAccountTypeEnum fundAccountTypeEnum = FundAccountTypeEnum.getByCode(type);
        String name = fundAccountEntity.getName();
        String memo = fundAccountEntity.getMemo();
        BigDecimal amount = fundAccountEntity.getInitialAmount();
        if (name != null && name.length() > ACCOUNT_NAME_MAX_LENGTH) {
            throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_NAME), ACCOUNT_NAME_MAX_LENGTH);
        }
        if (memo != null && memo.length() > AliasEnum.TEXTAREA.getMax()) {
            throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, I18nMessageUtil.getMessage(I18nStringConstant.MEMO), AliasEnum.TEXTAREA.getMax());
        }
        if (amount != null && amount.toPlainString().length() > AliasEnum.NUM.getMax()) {
            throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_INITIAL_AMOUNT), AliasEnum.NUM.getMax());
        }
        switch (fundAccountTypeEnum) {
            case BANK_ACCOUNT:
                String bankName = fundAccountEntity.getBankName();
                String bankAccount = fundAccountEntity.getBankAccount();
                if (bankName == null) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000001, fundAccountTypeEnum.getName(), I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_BANK));
                } else if (bankName.length() > AliasEnum.TEXT.getMax()) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_BANK), AliasEnum.TEXT.getMax());
                }
                if (bankAccount == null) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000001, fundAccountTypeEnum.getName(), fundAccountTypeEnum.getName());
                } else if (bankAccount.length() > AliasEnum.TEXT.getMax()) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, fundAccountTypeEnum.getName(), AliasEnum.TEXT.getMax());
                }
                break;
            case OTHER_ACCOUNT:
                String openingAccount = fundAccountEntity.getOpeningAccount();
                if (openingAccount == null) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000001, fundAccountTypeEnum.getName(), I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT));
                } else if (openingAccount.length() > AliasEnum.TEXT.getMax()) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT), AliasEnum.TEXT.getMax());
                }
                break;
            case ALIPAY_ACCOUNT:
                String alipayAccount = fundAccountEntity.getAlipayAccount();
                if (alipayAccount == null) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000001, fundAccountTypeEnum.getName(), fundAccountTypeEnum.getName());
                } else if (alipayAccount.length() > AliasEnum.TEXT.getMax()) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, fundAccountTypeEnum.getName(), AliasEnum.TEXT.getMax());
                }
                break;
            case WECHAT_ACCOUNT:
                String weChatAccount = fundAccountEntity.getWechartAccount();
                if (weChatAccount == null) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000001,fundAccountTypeEnum.getName(), fundAccountTypeEnum.getName());
                } else if (weChatAccount.length() > AliasEnum.TEXT.getMax()) {
                    throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000007, MessageConstant.MORE_THAN_LENGTH, fundAccountTypeEnum.getName(), AliasEnum.TEXT.getMax());
                }
                break;
            case CASH_ACCOUNT:
                break;
            default:
                throw new XbbException(FundAccountErrorCodeEnum.API_ERROR_1000002);
        }
    }

    /**
     * 资金账户是否存在关联流水信息
     * @param dataId 资金账户ID
     * @param corpid 公司ID
     * @return true->有  false->无
     * @throws XbbException error
     * @author zhouwq
     * @date 2020/3/21 14:21
     */
    private boolean verifyFundAccountInSheet(Long dataId, String corpid) throws XbbException{
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("accountId", dataId));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_FUND_ACCOUNT_FLOW.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_FUND_ACCOUNT_FLOW.getIndex());
        searchRequest.source(sourceBuilder);
        long count = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
        Integer paymentSheetAccount = paasProcessDataModel.getByFundAccountIdInPaymentSheet(corpid, dataId);
        Integer paySheetAccount = paasProcessDataModel.getByFundAccountIdInPaySheet(corpid, dataId);
        return count > 0 || paymentSheetAccount > 0 || paySheetAccount > 0;
    }

    /**
     * 判断资金账户是否可被关闭
     * @param corpid 公司ID
     * @return true or false
     * @author zhouwq
     * @date 2020/3/25 15:20
     */
    private boolean verifyFundAccountWhetherCanClose(String corpid) {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("enable", EnableEnum.OPEN.getCode());
        int count = fundAccountModel.getEntitysCount(params);
        return count > 1;
    }

    /**
     * 判断资金账户是否可被删除
     * @param dataId 公司ID
     * @param corpid 公司ID
     * @return true or false
     * @author zhouwq
     * @date 2020/3/25 15:20
     */
    private boolean verifyFundAccountWhetherCanDel(Long dataId, String corpid) {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("enable", EnableEnum.OPEN.getCode());
        params.put("negId", dataId);
        int count = fundAccountModel.getEntitysCount(params);
        return count > 0;
    }

    /**
     * 得到微信支付、支付宝支付、银联支付的默认支付账户，如果需要更新则塞入
     * @param accountObj
     * @param accountIdToEntity
     * @param attr 要更新的账户FundAccountEntity字段
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void formatUpdateAccountMap(JSONObject accountObj, Map<Long, FundAccountEntity> accountIdToEntity, String attr) {
        if (Objects.isNull(accountObj)) {
            return;
        }
        String preId = accountObj.getString(StringConstant.PREID);
        String currentId = accountObj.getString(StringConstant.CURRENTID);
        if (!Objects.equals(preId, currentId)) {
            if (StringUtil.isNotEmpty(preId)) {
                Long id = Long.valueOf(preId);
                FundAccountEntity fundAccountEntity = accountIdToEntity.containsKey(id) ? accountIdToEntity.get(id) : new FundAccountEntity();
                fundAccountEntity.setId(id);
                ReflectHelper.valueSet(fundAccountEntity, attr, BasicConstant.ZERO);
                accountIdToEntity.put(id, fundAccountEntity);
            }
            if (StringUtil.isNotEmpty(currentId)) {
                Long id = Long.valueOf(currentId);
                FundAccountEntity fundAccountEntity = accountIdToEntity.containsKey(id) ? accountIdToEntity.get(id) : new FundAccountEntity();
                fundAccountEntity.setId(id);
                ReflectHelper.valueSet(fundAccountEntity, attr, BasicConstant.ONE);
                accountIdToEntity.put(id, fundAccountEntity);
            }
        }
    }
}
